// Copyright 2008 web2me.dev
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package net.web2me.api;

import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import net.web2me.cli.Web2MeCli;
import net.web2me.multiurl.InvalidPatternException;
import net.web2me.multiurl.MultiUrl;
import net.web2me.multiurl.MultiUrlUtil;
import net.web2me.util.FileUtil;
import net.web2me.util.SiteStreamGenerator;
import net.web2me.util.UtilityException;

import org.apache.log4j.Logger;

public class ParserExecutor {

	private Logger logger = Logger.getLogger(ParserExecutor.class);

	private String parserName;

	private String dir;

	private String url;

	private boolean saveMetadata;

	private boolean saveHistory;

	public ParserExecutor(String parserName, String dir, String url,
			boolean saveHistory, boolean saveMetadata) {
		this.parserName = parserName;
		this.dir = dir;
		this.url = url;
		this.saveHistory = saveHistory;
		this.saveMetadata = saveMetadata;
	}

	public String execute() throws InvalidPatternException, ParserException,
			UtilityException {
		long start = 0;
		long stop = 0;
		
		Parsable parser = ParserFactory.getParser(parserName);

		List<MultiUrl> multiUrls = MultiUrlUtil.getMultiUrls(url);

		for (MultiUrl multi : multiUrls) {
			parser.setDir(dir
					+ (multi.getMatchedPattern().equals("") ? "" : "/"
							+ multi.getMatchedPattern()));
			parser.setUrl(multi.getUrl());

			String siteStream = SiteStreamGenerator.getStream(multi.getUrl());

			try {
				start = System.currentTimeMillis();
				
				parser.process(siteStream.toString());
				
				stop = System.currentTimeMillis();
			} catch (ProcessFinishedException e) {

			}
		}

		if (saveMetadata) {
			logger.debug("Saving the metadata");

			FileUtil.setContents(new File(dir + "/.web2me.metadata"), "Date: "
					+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss (Z)")
							.format(new Date()) + "\n" + "Parser: "
					+ parserName + "\n" + "URL: " + url + "\n" + "Destiny: "
					+ dir + "\n");
		}

		if (saveHistory) {
			FileUtil.appendContents(
					new File(getRealPath() + "/.web2me.history"),
					new SimpleDateFormat("yyyy-MM-dd HH:mm:ss (Z)")
							.format(new Date())
							+ "\t"
							+ parserName
							+ "\t"
							+ url
							+ "\t"
							+ dir
							+ "\n");
		}
		
		return calcuteTime(start, stop);
	}

	/**
	 * Gets the real physical path where the jar is located
	 * 
	 * @return The real path
	 */
	private String getRealPath() {
		URL currentDir = Web2MeCli.class.getResource("/log4j-debug.properties");
		String fullPath = currentDir.getFile().toString().replace("file:", "");
		// 2 times is ok
		fullPath = fullPath.substring(0, fullPath.lastIndexOf("/"));
		fullPath = fullPath.substring(0, fullPath.lastIndexOf("/"));

		return fullPath;
	}
	
	private static String calcuteTime(long start, long stop) {
		long ms = stop - start;

		long sec = ms / 1000;
		ms = ms % 1000;

		long min = sec / 60;
		sec = sec % 60;

		long hours = min / 60;
		min = min % 60;

		return hours + " hours, " + min + " minutes and " + sec + " seconds";
	}

}
